package com.txhy.certificatechain.ui.fragment.bottomnavigation;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.ninetripods.aopermission.permissionlib.annotation.NeedPermission;

import com.txhy.certificatechain.R;
import com.txhy.certificatechain.api.UrlAddress;
import com.txhy.certificatechain.model.bean.BannerBean;
import com.txhy.certificatechain.model.bean.NewsBean;
import com.txhy.certificatechain.model.bean.UserBean;
import com.txhy.certificatechain.presenter.home.HomePagerPresenter;
import com.txhy.certificatechain.ui.activity.base.BaseFragment;
import com.txhy.certificatechain.ui.activity.pay.ScannerActivity;
import com.txhy.certificatechain.ui.adapter.DialogNameAdapter;
import com.txhy.certificatechain.ui.adapter.FragHomeGdThreeAdapter;
import com.txhy.certificatechain.ui.manager.ImageLoaderManager;
import com.txhy.certificatechain.ui.view.index.IndexPagerView;
import com.txhy.certificatechain.utils.CommUtils;
import com.txhy.certificatechain.utils.GsonUtil;
import com.txhy.certificatechain.utils.PrefUtil;
import com.txhy.certificatechain.utils.ToastUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.bgabanner.BGABanner;

/*
 * -----------------------------------------------------------------
 * Copyright (C) 2018-2030, by your company, All rights reserved.
 * -----------------------------------------------------------------
 * 文    件: IndexFragment.java
 * 作    者: 侯建军
 * 版    权: 1.0.0
 * 描    述: 首页--底部导航
 * 创建时间: 2018/9/19 17:15
 * 更新时间：2018/9/19 17:15
 * -----------------------------------------------------------------
 * 2018/9/19 17:15: 创建 IndexFragment.java (侯建军);
 * -----------------------------------------------------------------
 */
public class IndexFragment extends BaseFragment<IndexPagerView, HomePagerPresenter> implements IndexPagerView {
    private final int RESULT_REQUEST_CODE = 1;

    @BindView(R.id.gd_home_three)
    GridView gd_home_three;

    @BindView(R.id.mBanner)
    BGABanner mBanner;

    @BindView(R.id.flipper)
    ViewFlipper flipper;
    @BindView(R.id.img_add)
    ImageView img_add;
    @BindView(R.id.tv_name)
    TextView tv_name;
    private UserBean user;
    private UserBean.DataEntity.MapEntity userMap;


    @BindView(R.id.ll_saoyisao)
    LinearLayout ll_saoyisao;
    @BindView(R.id.ll_wodezheng)
    LinearLayout ll_wodezheng;
    @BindView(R.id.ll_shoukuan)
    LinearLayout ll_shoukuan;
    @BindView(R.id.ll_fukuan)
    LinearLayout ll_fukuan;

    @BindView(R.id.ll_dianzihe)
    LinearLayout ll_dianzihe;
    @BindView(R.id.ll_zhuanzhang)
    LinearLayout ll_zhuanzhang;
    @BindView(R.id.ll_qiyeren)
    LinearLayout ll_qiyeren;
    @BindView(R.id.ll_kaitong)
    LinearLayout ll_kaitong;


    @BindView(R.id.ll_wodezhang)
    LinearLayout ll_wodezhang;
    @BindView(R.id.ll_qiyezheng)
    LinearLayout ll_qiyezheng;
    @BindView(R.id.ll_qiyeguan)
    LinearLayout ll_qiyeguan;


    @Override
    protected HomePagerPresenter createPresenter() {
        return new HomePagerPresenter();
    }

    public static IndexFragment newInstance() {
        return new IndexFragment();
    }

    /**
     * 顶部内容
     * @return
     */
    @Override
    protected int provideContentViewId() {
        return R.layout.frag_index_top;
    }

    @Override
    public void initView(View rootView) {
        super.initView(rootView);
        setLoginData();
        gd_home_three.setAdapter(new FragHomeGdThreeAdapter(null, getContext()));

    }


    public void setLoginData() {
        mPresenter.getBannerData("appLb");
        mPresenter.getNewsData("1");

        if (PrefUtil.getLoginBoolean(getActivity())) {
            user = PrefUtil.getUserString(getActivity());
            userMap = PrefUtil.getUserBean(getActivity());
            tv_name.setText(userMap.getEnterpriseName());

            switch (userMap.getUserType()) {
                case "0":
                    ll_qiyezheng.setVisibility(View.GONE);
                    ll_qiyeguan.setVisibility(View.GONE);
                    ll_wodezheng.setVisibility(View.VISIBLE);
                    ll_qiyeren.setVisibility(View.VISIBLE);
                    break;
                case "1":
                    ll_qiyezheng.setVisibility(View.VISIBLE);
                    ll_qiyeguan.setVisibility(View.VISIBLE);
                    ll_wodezheng.setVisibility(View.GONE);
                    ll_qiyeren.setVisibility(View.GONE);
                    break;
            }
            if (TextUtils.isEmpty(userMap.getAccountNo())) {
                ll_wodezhang.setVisibility(View.GONE);
                ll_kaitong.setVisibility(View.VISIBLE);
            } else {
                ll_kaitong.setVisibility(View.GONE);
                ll_wodezhang.setVisibility(View.VISIBLE);
            }


        } else {
            //设置文本
            tv_name.setText("请登录");
        }
    }

    /**
     *
     */
    @Override
    public void initListener() {
        super.initListener();
        img_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommUtils.showHomePopup(getActivity(), img_add);
            }
        });
    }

    /**
     * 顶部导航事件
     * @param view
     */
    @OnClick({R.id.linear_name, R.id.ll_saoyisao, R.id.ll_qiyeguan, R.id.ll_kaitong, R.id.ll_qiyezheng, R.id.ll_wodezhang, R.id.ll_wodezheng,
            R.id.ll_shoukuan, R.id.ll_fukuan, R.id.ll_dianzihe, R.id.ll_zhuanzhang, R.id.ll_qiyeren})
    public void onViewClicked(View view) {
        if (!PrefUtil.getLoginBoolean(getActivity())) {
            CommUtils.doToLoad(getActivity());
            return;
        }
        switch (view.getId()) {
            case R.id.linear_name://下拉选择角色
                setLoginStatus();
                break;

            case R.id.ll_saoyisao://扫一扫
                goScanner();
                break;
            case R.id.ll_wodezheng://我的证件
               /* Intent intent = new Intent(getActivity(), MyCertificateActivity.class);
                intent.putExtra("type", 0);
                startActivity(intent);*/

                break;
            case R.id.ll_shoukuan://收款
//                startActivity(new Intent(getActivity(), PayMentActivity.class));
                break;
            case R.id.ll_fukuan://付款
//                startActivity(new Intent(getActivity(), ReceipActivity.class));

                break;
            case R.id.ll_dianzihe://电子合同
//                startActivity(new Intent(getActivity(), ElectrContractActivity.class));

                break;
            case R.id.ll_zhuanzhang://转账
//                startActivity(new Intent(getActivity(), AddressListActivity.class));

                break;
            case R.id.ll_qiyeren://企业认证
//                startActivity(new Intent(getActivity(), EnterpriseRegistrationActivity.class));
                break;
            case R.id.ll_kaitong://开通账户

//                Intent intent2 = new Intent(getActivity(), WebViewActivity.class);
//                intent2.putExtra(WEB_URL, UrlAddress.JYBOPEN_URL);
//                intent2.putExtra("type",0);
//                startActivity(intent2);
                break;
            case R.id.ll_qiyezheng://企业证照
//                Intent intent1 = new Intent(getActivity(), MyCertificateActivity.class);
//                intent1.putExtra("type", 1);
//                startActivity(intent1);
                break;
            case R.id.ll_qiyeguan://企业管理
//                startActivity(new Intent(getActivity(), BusinessActivity.class));
                break;
            case R.id.ll_wodezhang://我的账户
//                startActivity(new Intent(getActivity(), MyJybActivity.class));
                break;
        }
    }

    /**
     * 扫一扫
     */
    @NeedPermission(value = {Manifest.permission.CAMERA}, requestCode = 0)
    private void goScanner() {
        Intent intent = new Intent(getActivity(), ScannerActivity.class);
        startActivity(intent);
    }


    @Override
    public void getBannerSuccess(String user) {
        BannerBean bean = GsonUtil.GsonToBean(user, BannerBean.class);
        //设置轮播图
        mBanner.setData(R.layout.item_banner, bean.getData(), null);
        mBanner.setAdapter(new BGABanner.Adapter<View, BannerBean.DataEntity>() {
            @Override
            public void fillBannerItem(BGABanner banner, View itemView, BannerBean.DataEntity model, int position) {
                ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
                imageView.setImageResource(R.mipmap.ic_launcher);
                ImageLoaderManager.LoadImage(getContext(), UrlAddress.IMGBASE_URL + model.getImgUrl(), imageView);
            }
        });
        mBanner.setDelegate(new BGABanner.Delegate<View, BannerBean.DataEntity>() {
            @Override
            public void onBannerItemClick(BGABanner banner, View itemView, BannerBean.DataEntity model, int position) {
//                WebViewActivity.runActivity(getContext(), model.getUrl());

            }
        });
    }

    @Override
    public void getBannerFail(String msg) {
        ToastUtil.showLong(getActivity(), msg);
    }

    @Override
    public void getNewsSuccess(String user) {
        NewsBean bean = GsonUtil.GsonToBean(user, NewsBean.class);
        for (int i = 0; i < bean.getData().size(); i++) {
            final View ll_content = View.inflate(getActivity(), R.layout.item_flipper, null);
            TextView tv_content = (TextView) ll_content.findViewById(R.id.tv_content);
            TextView tv_content_two = (TextView) ll_content.findViewById(R.id.tv_content_two);
            ImageView img_img = (ImageView) ll_content.findViewById(R.id.img_img);
            tv_content.setText(bean.getData().get(i).getTitle());
            tv_content_two.setText(bean.getData().get(i).getDetail());
            ImageLoaderManager.LoadImage(getActivity(), UrlAddress.IMGBASE_URL + bean.getData().get(i).getLogoUrl(), img_img);
            flipper.addView(ll_content);
        }
    }

    @Override
    public void getNewsFail(String msg) {
        ToastUtil.showLong(getActivity(), msg);
    }

    private void setLoginStatus() {
        showWaitingDialog("正在加载数据...");
        OkGo.<String>post(UrlAddress.GETENTERPRI_URL)//
                .tag(getActivity())//
                .params("userId", PrefUtil.getUserString(getActivity()).getData().getUserId() + "")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (GsonUtil.GsonGetStatus(response.body()) == 200) {
                            PrefUtil.setUserString(getActivity(), response.body());
                            showNameDialog(getActivity(), tv_name, response.body());
                            hideWaitingDialog();

                        } else {
                            ToastUtil.showLong(getActivity(), GsonUtil.GsonGetMsg(response.body()));
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtil.showLong(getActivity(), "请求失败请检查网络");
                    }
                });
    }

    private Dialog mDialog;

    //首页显示人登录的类型
    public Dialog showNameDialog(final Context context, final TextView tvName, String data) {
        hideNameDialog();
        UserBean dataUserBean = GsonUtil.GsonToBean(data, UserBean.class);

        mDialog = new Dialog(context, R.style.MyDialog);
        LinearLayout root = (LinearLayout) LayoutInflater.from(context).inflate(
                R.layout.dialog_name, null);
        ListView lv_content = root.findViewById(R.id.lv_content);
        final List<UserBean.DataEntity.MapEntity> list = dataUserBean.getData().getMap();

        list.get(PrefUtil.getShengType(context)).setCheck(true);
        final DialogNameAdapter adapter = new DialogNameAdapter(list, context);
        lv_content.setAdapter(adapter);
        lv_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int i = 0; i < list.size(); i++) {
                    list.get(i).setCheck(false);
                }
                list.get(position).setCheck(true);
                PrefUtil.setShengType(context, position);
                adapter.cotifyAdapter(list);
                tvName.setText(list.get(position).getEnterpriseName());

                UserBean.DataEntity.MapEntity user = list.get(position);
                switch (user.getUserType()) {
                    case "0":
                        ll_qiyezheng.setVisibility(View.GONE);
                        ll_qiyeguan.setVisibility(View.GONE);
                        ll_wodezheng.setVisibility(View.VISIBLE);
                        ll_qiyeren.setVisibility(View.VISIBLE);
                        break;
                    case "1":
                        ll_qiyezheng.setVisibility(View.VISIBLE);
                        ll_qiyeguan.setVisibility(View.VISIBLE);
                        ll_wodezheng.setVisibility(View.GONE);
                        ll_qiyeren.setVisibility(View.GONE);
                        break;
                }
                if (TextUtils.isEmpty(user.getAccountNo())) {
                    ll_wodezhang.setVisibility(View.GONE);
                    ll_kaitong.setVisibility(View.VISIBLE);
                } else {
                    ll_kaitong.setVisibility(View.GONE);
                    ll_wodezhang.setVisibility(View.VISIBLE);
                }

                hideNameDialog();

            }
        });
        mDialog.setContentView(root);
        Window dialogWindow = mDialog.getWindow();
        dialogWindow.setGravity(Gravity.TOP);
        mDialog.setCancelable(true);
        dialogWindow.setWindowAnimations(R.style.dialogstyle_name); // 添加动画
        WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        lp.x = 0; // 新位置X坐标
        lp.y = -20; // 新位置Y坐标
        lp.width = ((int) context.getResources().getDisplayMetrics().widthPixels); // 宽度
        root.measure(0, 0);
        lp.height = root.getMeasuredHeight();
        lp.alpha = 9f; // 透明度
        dialogWindow.setAttributes(lp);
        mDialog.show();
        if (list.size() == 1) {
            mDialog.dismiss();
            ToastUtil.showLong(context, "您还没有注册任何企业");
        }
        return mDialog;
    }
    /**
     *
     */
    public void hideNameDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
    }
}

